﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using my_webapi_demo.ApiRouteEx;
using my_webapi_demo.Auth;
using my_webapi_demo.Db;
using my_webapi_demo.Db.Entity;

namespace my_webapi_demo.Controllers;

[ApiRoute.Order]
public class HomeController(ILogger<HomeController> logger)
{
    private readonly ILogger<HomeController> _logger = logger;

    /// <summary>
    /// Hello
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public string Hello() => "hello";

    /// <summary>
    /// 获取当前时间
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public string GetTime()
    {
        var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        _logger.LogInformation("当前时间：" + time);
        return time;
    }

    /// <summary>
    /// 抛出异常
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public void Error()
    {
        var ww = "";
        ww = null;
        var waa = ww.ToString();
        throw new Exception("出错了");
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    [AllowAnonymous]
    public string Login()
    {
        var token = new TokenData(Guid.Parse("02e2ff08-b2b0-449d-a72a-46ce99ea6107"), "孙小双", "huasky");
        AuthSession.Create(token);
        return token.ToTokenString();
    }

    /// <summary>
    /// 读取json
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public object GetJson() => new { Name = "孙小双", Age = 18 };

    /// <summary>
    /// 获取用户
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public object GetStaff([FromServices] UserSession session)
    {
        var data = session.GetSessionData();
        return new
        {
            data.StaffId,
            data.StaffName
        };
    }

    /// <summary>
    /// 创建报告
    /// </summary>
    /// <param name="report"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<ReportEntity> CreateReport(ReportEntity report)
    {
        using var db = new HuaskyDbContext();
        db.Report.Add(report);
        await db.SaveChangesAsync();
        return report;
    }

    /// <summary>
    /// 创建报告
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public List<ReportEntity> GetReport()
    {
        using var db = new HuaskyDbContext();
        return [.. db.Report];
    }

}
